//
//  WorkManQRController.m
//  operativeSide
//
//  Created by 王春程 on 16/6/8.
//  Copyright © 2016年 com.caocaod.www. All rights reserved.
//

#import "WorkManQRController.h"
#import "CCDPostWorkManTilView.h"
#import <AVFoundation/AVFoundation.h>
#define maskAlpha 0.3
#define kLineMinY (VIEW_HEIGHT-200-64)/2
#define kLineMaxY (VIEW_HEIGHT-200-64)/2+200

static const float kReaderViewWidth = 200;
static const float kReaderViewHeight = 200;

@interface WorkManQRController()<AVCaptureMetadataOutputObjectsDelegate,ZBarReaderViewDelegate>

@property (strong,nonatomic)                AVCaptureDevice * device;

@property (strong,nonatomic)                AVCaptureDeviceInput * input;

@property (strong,nonatomic)                AVCaptureMetadataOutput * output;

@property (strong,nonatomic)                AVCaptureSession * session;

@property (strong,nonatomic)                AVCaptureVideoPreviewLayer * preview;


@property (nonatomic, strong)               UIImageView *line;//交互线
@property (nonatomic, strong)               NSTimer *lineTimer;//交互线控制
@property (strong, nonatomic)               AVAudioPlayer *player;
@property (nonatomic, strong)               UILabel *bag;
@property (nonatomic, strong)               UILabel *numberLabel;

@property (nonatomic, strong)               UIView *bottomView; // 弹框底部视图
@property (nonatomic, strong)               UILabel *bagNumber; // 弹框包号
@property (nonatomic, strong)               UILabel *countLabel; // 弹框件数
@property (strong, nonatomic)               UILabel *number;
@property (nonatomic, strong)               UIView *myView; // 弹框选择视图
@property (nonatomic, strong)               UILabel *bagLabel;
@property (nonatomic, strong)               UIButton *cityBtn;
@property (nonatomic, strong)               UIButton *cityBtn1;
@property (nonatomic, strong)               UIButton *cityBtn2;
@property (nonatomic, strong)               UIButton *cityBtn3;

@property (strong, nonatomic)               NSString *QRString;
@property (assign, nonatomic)               NSInteger allIndex;
@property (strong, nonatomic)               ZBarReaderView *readview;

@end
@implementation WorkManQRController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setNavBar];
//    [self InitScan];
    [self initZbarReader];
}


#pragma mark -_- initZbarReader
- (void)initZbarReader {
    
    //检测系统相机是否可用
    NSError *error;
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:&error];
    if (error)
    {
        NSString *reasonString = error.userInfo[@"NSLocalizedFailureReason"];
        if([reasonString isEqualToString:@"This app is not authorized to use Back Camera."]) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在iPhone的\"设置-隐私-相机\"中允许使用相机" preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [alert removeFromParentViewController];
                [self.navigationController popViewControllerAnimated:YES];
            }]];
            
            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
                
                [alert addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    dispatch_after(0.2, dispatch_get_main_queue(), ^{
                        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                        if ([[UIApplication sharedApplication] canOpenURL:url]) {
                            [[UIApplication sharedApplication] openURL:url];
                        }
                    });
                    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC);
                    dispatch_after(time, dispatch_get_main_queue(), ^{
                        [self.navigationController popViewControllerAnimated:YES];
                    });
                }]];
            }
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];
        } else {
            [self.view makeToast:@"相机不可用,请检查您的相机" duration:1.5 position:@"center"];
            dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC);
            dispatch_after(time, dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
        return;
    }
    
    _readview = [ZBarReaderView new];
    //自定义大小
    _readview.frame = CGRectMake(0, 64, VIEW_WIDTH, VIEW_HEIGHT - 64);
    _readview.readerDelegate = self;
    //将其照相机拍摄视图添加到要显示的视图上
    [self.view addSubview:self.readview];
    
    [self initPickerView];
    [self initPlayer];
    [self startScanQRCode];
    //二维码/条形码识别设置
    ZBarImageScanner *scanner = self.readview.scanner;
    [scanner setSymbology: ZBAR_I25
                   config: ZBAR_CFG_ENABLE
                       to: 0];
    //开启相机追踪
    self.readview.tracksSymbols = YES;
    self.readview.trackingColor = [UIColor greenColor];
    //启动，必须启动后，手机摄影头拍摄的即时图像菜可以显示在readview上
    [self.readview start];
}

#pragma mark -_- ZbarReadViewDelegate
- (void)readerView:(ZBarReaderView *)readerView didReadSymbols:(ZBarSymbolSet *)symbols fromImage:(UIImage *)image {
    [self stopScanQRCode];
    [self.player play];
    ZBarSymbol *symbol = nil;
    for(symbol in symbols)
        break;
    NSString *resultString = symbol.data;
    if (resultString && ![resultString isEqualToString:@""] && resultString.length > 0)
    {
        NSString *firstChar = [resultString substringToIndex:1];
        NSLog(@"%@",firstChar);
        if(![firstChar isEqualToString:@"P"]) {
            [self.view makeToast:@"请扫描正确的件" duration:1 position:@"center"];
            [self startScanQRCode];
        } else {
            [self postDataWithQRCode:resultString];
        }
    }
    //不需要连扫则需要加上停止
//    [readerView stop];
}

- (void)readerView:(ZBarReaderView *)readerView didStopWithError:(NSError *)error {
    WS(weakSelf);
    if(error) {
        [self.view makeToast:@"请扫描正确的二维码" duration:1.5 position:@"center"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.readview start];
        });
    }
}

#pragma mark - 导航栏界面以及方法
///设置导航栏
- (void)setNavBar {
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 64)];
    backView.backgroundColor = RGB(70, 153, 223);
    [self.view addSubview:backView];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake((VIEW_WIDTH-100)/2, 20, 100, 44)];
    titleLabel.font = [UIFont systemFontOfSize:15];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.text = @"扫描二维码";
    [backView addSubview:titleLabel];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"cp_back"] forState:UIControlStateNormal];
    backBtn.contentMode = UIViewContentModeScaleAspectFill;
    [backBtn setFrame:CGRectMake(0, 20, 44, 44)];
    [backView addSubview:backBtn];
    [backBtn addTarget:self action:@selector(backBtnAction:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - 设置扫面区域外的遮罩以及图片等
- (void)initPickerView
{
    //画中间的基准线
    _line = [[UIImageView alloc] initWithFrame:CGRectMake((VIEW_WIDTH - 300) / 2.0, kLineMinY, 300, 12 * 300 / 320.0)];
    [_line setImage:[UIImage imageNamed:@"ff_QRCodeScanLine"]];
    [self.view addSubview:_line];
    
    //最上部view
    UIView* upView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, VIEW_WIDTH, kLineMinY-64)];//80
    upView.alpha = maskAlpha;
    upView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:upView];
    
    //左侧的view
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, kLineMinY, (VIEW_WIDTH - kReaderViewWidth) / 2.0, kReaderViewHeight)];
    leftView.alpha = maskAlpha;
    leftView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:leftView];
    
    //右侧的view
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(VIEW_WIDTH - CGRectGetMaxX(leftView.frame), kLineMinY, CGRectGetMaxX(leftView.frame), kReaderViewHeight)];
    rightView.alpha = maskAlpha;
    rightView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:rightView];
    
    CGFloat space_h = VIEW_HEIGHT - kLineMaxY;
    
    //底部view
    UIView *downView = [[UIView alloc] initWithFrame:CGRectMake(0, kLineMaxY, VIEW_WIDTH, space_h)];
    downView.alpha = maskAlpha;
    downView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:downView];
    
    //四个边角
    UIImage *cornerImage = [UIImage imageNamed:@"ScanQR1"];
    
    //左侧的view
    UIImageView *leftView_image = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(leftView.frame) - cornerImage.size.width / 2.0, CGRectGetMaxY(upView.frame) - cornerImage.size.height / 2.0, cornerImage.size.width, cornerImage.size.height)];
    leftView_image.image = cornerImage;
    [self.view addSubview:leftView_image];
    
    cornerImage = [UIImage imageNamed:@"ScanQR2"];
    
    //右侧的view
    UIImageView *rightView_image = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMinX(rightView.frame) - cornerImage.size.width / 2.0, CGRectGetMaxY(upView.frame) - cornerImage.size.height / 2.0, cornerImage.size.width, cornerImage.size.height)];
    rightView_image.image = cornerImage;
    [self.view addSubview:rightView_image];
    
    cornerImage = [UIImage imageNamed:@"ScanQR3"];
    
    //底部view
    UIImageView *downView_image = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(leftView.frame) - cornerImage.size.width / 2.0, CGRectGetMinY(downView.frame) - cornerImage.size.height / 2.0, cornerImage.size.width, cornerImage.size.height)];
    downView_image.image = cornerImage;
    [self.view addSubview:downView_image];
    
    cornerImage = [UIImage imageNamed:@"ScanQR4"];
    
    UIImageView *downViewRight_image = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMinX(rightView.frame) - cornerImage.size.width / 2.0, CGRectGetMinY(downView.frame) - cornerImage.size.height / 2.0, cornerImage.size.width, cornerImage.size.height)];
    downViewRight_image.image = cornerImage;
    //downView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:downViewRight_image];
    
    //说明label
    UILabel *labIntroudction = [[UILabel alloc] init];
    labIntroudction.backgroundColor = [UIColor clearColor];
    labIntroudction.frame = CGRectMake(0, CGRectGetMinY(downView.frame) + 25, VIEW_WIDTH, 20);
    labIntroudction.textAlignment = NSTextAlignmentCenter;
    labIntroudction.font = [UIFont boldSystemFontOfSize:13.0];
    labIntroudction.textColor = [UIColor whiteColor];
    labIntroudction.text = @"请将二维码置于框内,即可自动扫描";
    [self.view addSubview:labIntroudction];
    
    UIView *scanCropView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(leftView.frame) - 1,kLineMinY,VIEW_WIDTH- 2 * CGRectGetMaxX(leftView.frame) + 2, kReaderViewHeight + 1)];
    scanCropView.layer.borderColor = [UIColor whiteColor].CGColor;
    scanCropView.layer.borderWidth = 1.0;
    scanCropView.alpha = 0.9;
    [self.view addSubview:scanCropView];
}

#pragma mark - buttonAction
- (void)backBtnAction:(UIButton *)sender {
    [self cancleScanQRCode];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)initPlayer {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"5383" ofType:@"wav"];
    NSData *playerData = [NSData dataWithContentsOfFile:path];
    NSError *error;
    _player = [[AVAudioPlayer alloc] initWithData:playerData error:&error];
}

#pragma mark - 扫描二维码开始或者停止方法
- (void)startScanQRCode
{
    _lineTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 / 20 target:self selector:@selector(animationLine) userInfo:nil repeats:YES];
    
//    [self.session startRunning];
    
    NSLog(@"start reading");
}

- (void)stopScanQRCode
{
    if (_lineTimer)
    {
        [_lineTimer invalidate];
        _lineTimer = nil;
    }
    
//    [self.session stopRunning];
    
    NSLog(@"stop reading");
}

//取消扫描
- (void)cancleScanQRCode
{
    [self stopScanQRCode];
    
    if (self.ScanQRCodeCancelBlock)
    {
        self.ScanQRCodeCancelBlock(self);
    }
    NSLog(@"cancle reading");
}


#pragma mark - 扫描线的上下移动
- (void)animationLine
{
    __block CGRect frame = _line.frame;
    
    static BOOL flag = YES;
    
    if (flag)
    {
        frame.origin.y = kLineMinY;
        flag = NO;
        [UIView animateWithDuration:1.0 / 20 animations:^{
            frame.origin.y += 5;
            _line.frame = frame;
        }];
    }
    else
    {
        if (_line.frame.origin.y >= kLineMinY)
        {
            if (_line.frame.origin.y >= kLineMaxY - 12)
            {
                frame.origin.y = kLineMinY;
                _line.frame = frame;
                flag = YES;
            }
            else
                [UIView animateWithDuration:1.0 / 20 animations:^{
                    frame.origin.y += 5;
                    _line.frame = frame;
                }];
        }
        else
        {
            flag = !flag;
        }
    }
}

- (void)postDataWithQRCode:(NSString *)QRString {
    NSString *baseUrl = @"http://serv.caocaod.com/work/couriers/doSend";
    NSDictionary *dict = @{
                           @"pieceId":self.piece.jPiecesIdentifier,
                           @"pieceCode":QRString,
                           @"time" : [NSString getCurrentTime]
                           };
    
    NSString *timeString = [NSString getJsonStringWithDic:dict];
    NSData *praseData = [AESSecurityTool encryptAndBase64ToDataWithString:timeString];
    NSString *praseString = [[NSString alloc] initWithData:praseData encoding:NSUTF8StringEncoding];
    NSDictionary *postDict;
    if(UserValue(@"cookie")) {
        NSDictionary *cookie = UserValue(@"cookie");
        postDict =  @{
                      @"verApp":[NSString getAppVer],
                      @"app":@"com.caocaod.work",
                      @"platform":@"iOS",
                      @"aes":praseString,
                      cookie[@"name"]:cookie[@"token"]
                      };
    } else {
        postDict =  @{
                      @"verApp":[NSString getAppVer],
                      @"app":@"com.caocaod.work",
                      @"platform":@"iOS",
                      @"aes":praseString
                      };
    }

    WS(ws);
    [self postWithUrl:baseUrl params:postDict progressView:nil successBlock:^(id JSON) {
        NSDictionary *newdict = JSON;
        if(1 == [newdict[@"result"] integerValue]) {
            NSString *aesString = newdict[@"aes"];
            NSString *aesPrsaeString = [AESSecurityTool decryptAndBase64ToStringWithString:aesString];
            NSDictionary *newDictionary = [NSDictionary dictionaryWithJsonString:aesPrsaeString];
            
            //保存COOkie
            NSDictionary *cookieDic = newDictionary[@"cookie"];
            if(UserValue(@"cookie")) {
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"cookie"];
            }
            UserSetValueForKey(cookieDic, @"cookie");
            
            if(1 == [newDictionary[@"result"] integerValue]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"haveRecReload" object:@"over"];
                [self.navigationController popViewControllerAnimated:YES];
                NSLog(@"成功了");
            }else {
                [ws.view makeToast:newDictionary[@"msg"] duration:1.0 position:@"center"];
                dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
                dispatch_after(time, dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
        } else {
            if((-10 == [newdict[@"result"] integerValue])) {
                if(ws.allIndex <= 2) {
                    [ws createAesKey];
                    ws.allIndex ++;
                } else {
                    [ws.view makeToast:@"服务器错误，请稍候再试" duration:1.5 position:@"center"];
                    ws.allIndex = 0;
                }
            }
        }
    } faithBlock:^(NSError *error) {
        [ws.view makeToast:@"请检查您的网络重新扫描" duration:1.0 position:@"center"];
        dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC);
        dispatch_after(time, dispatch_get_main_queue(), ^{
            [self startScanQRCode];
        });
        NSLog(@"%@",error);
    }];
}


#pragma mark -_- 废弃
/** 废弃
- (void)InitScan
{
    NSError *error;
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:&error];
    if (error)
    {
        NSString *reasonString = error.userInfo[@"NSLocalizedFailureReason"];
        if([reasonString isEqualToString:@"This app is not authorized to use Back Camera."]) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在iPhone的\"设置-隐私-相机\"中允许使用相机" preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [alert removeFromParentViewController];
                [self.navigationController popViewControllerAnimated:YES];
            }]];
            
            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
                
                [alert addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    dispatch_after(0.2, dispatch_get_main_queue(), ^{
                        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                        if ([[UIApplication sharedApplication] canOpenURL:url]) {
                            [[UIApplication sharedApplication] openURL:url];
                        }
                    });
                    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC);
                    dispatch_after(time, dispatch_get_main_queue(), ^{
                        [self.navigationController popViewControllerAnimated:YES];
                    });
                }]];
            }
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];
        } else {
            [self.view makeToast:@"相机不可用,请检查您的相机" duration:1.5 position:@"center"];
            dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC);
            dispatch_after(time, dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
        return;
    }
    
    // Output
    _output = [[AVCaptureMetadataOutput alloc]init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // Session
    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    
    if ([_session canAddInput:self.input])
        
    {
        
        [_session addInput:self.input];
        
    }
    
    if ([_session canAddOutput:self.output])
        
    {
        
        [_session addOutput:self.output];
        
    }
    
    // 条码类型 AVMetadataObjectTypeQRCode
    //    _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];
    [_output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeUPCECode,AVMetadataObjectTypeCode39Code,AVMetadataObjectTypeCode39Mod43Code,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode93Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypePDF417Code,AVMetadataObjectTypeAztecCode,AVMetadataObjectTypeInterleaved2of5Code,AVMetadataObjectTypeITF14Code,AVMetadataObjectTypeDataMatrixCode]];
    
    // Preview
    
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:_session];
    
    _preview.videoGravity =AVLayerVideoGravityResizeAspectFill;
    
    _preview.frame =self.view.layer.bounds;
    
    [self.view.layer insertSublayer:_preview atIndex:0];
    
    // Start
    [self initPickerView];
    [self startScanQRCode];
    
}

#pragma mark - 获取扫描结果
#pragma mark AVCaptureMetadataOutputObjectsDelegate

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{   [self.player play];
    //有结果
    if (metadataObjects.count > 0)
    {
        [self stopScanQRCode];
        AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
        
        if (obj.stringValue && ![obj.stringValue isEqualToString:@""] && obj.stringValue.length > 0)
        {
            NSString *firstChar = [obj.stringValue substringToIndex:1];
            NSLog(@"%@",firstChar);
            if(![firstChar isEqualToString:@"P"]) {
                if (self.ScanQRCodeSuccessBlock) {
                    self.ScanQRCodeSuccessBlock(self,obj.stringValue);
                }
                [self.view makeToast:@"请扫描正确的件" duration:1 position:@"center"];
                [self startScanQRCode];
            } else {
                [self postDataWithQRCode:obj.stringValue];
            }
        }
        else
        {
            if (self.ScanQRCodeFailBlock) {
                self.ScanQRCodeFailBlock(self);
            }
        }
    }
    //无结果
    else
    {
        if (self.ScanQRCodeFailBlock) {
            self.ScanQRCodeFailBlock(self);
        }
    }
}
*/
@end
